/*********************************************************************
Authors: Vineet Gupta
Project: ETS
Purpose: Create costs tables
			
Date created: 14 January 2022
Version: 	  STATA 16 MP

Last edited: 14 June 2022
Edited by: 	 Vineet, Kaixin
*********************************************************************/

clear all
clear matrix
set more off
set linesize 255
pause on

use "$PHONE_DATA_OUT/apcd_panel_plant.dta", clear

**********************

* make sure key data is available + plant is used in analysis
keep if D_treatment==1 & D_analysis==1
keep if !missing(emissions_conc_etsbl) & !missing(emissions_mass_etsbl)

* make sure a boiler is present
merge 1:1 gpcb_id using "$BASELINE_DATA_IN/BaselineCovariates_318i.dta", keepusing(plant_boi_cap industry_id vol_flow_etsbl) keep(master match) nogen
keep if plant_boi_cap!=0


* select several plants by boiler capacity roughly corresponding to 5th, 35th, 65th, and 95th percentiles
_pctile plant_boi_cap, percentiles(5, 35, 65, 95)
dis "5th: `r(r1)', 35th: `r(r2)', 65th: `r(r3)', and 95th: `r(r4)'"
keep if inlist(gpcb_id, 101235423, 104860678, 105331799, 112914615)
sort plant_boi_cap
list plant_boi_cap

* Previously, the code to select these plants was below (lines 43 to 53), but due to the anonymization 
* process, the sort order has changed and the same plants are not selected as in the paper.
* For the purpose of replicating the paper exhibits, the plants are selected manually above.

* sort plant_boi_cap, stable
* gen size_n = _n

* quietly: count 
* local N_plants `r(N)'
* local grp1 = floor(`N_plants'*5/100)
* local grp2 = floor(`N_plants'*35/100)
* local grp3 = floor(`N_plants'*65/100)
*local grp4 = floor(`N_plants'*95/100)

*keep if inlist(size_n, `grp1', `grp2', `grp3', `grp4')


* replace baseline mass with inlet mass
gen emissions_inlet_hr = vol_flow_etsbl/1000000 * 2000 // assume inlet conc is 2000 mg/Nm3

* select pertinent data; reshape for easier manipulation
keep plant_boi_cap heatoutput apcd_unitcost_* emissions_inlet_hr
reshape long apcd_unitcost_install_ apcd_unitcost_ope_ apcd_unitcost_maint_, i(heatoutput plant_boi_cap) j(apcd) string

// ASSUME CYCLONE PRESENT -------------------------------------------
preserve 
* construct key variables 

	* create place-holder assumed unabated pollution
	gen emissions_inlet_month = emissions_inlet_hr * 16 * 25 * 0.2 // * hours/day * days/month * one cyclone present
	drop emissions_inlet_hr
	label var emissions_inlet_month "Assumed uncontrolled pollution (kg/month)"

	* create monthly amortized flow costs
	rename apcd_unitcost_*_ cost_*
	replace cost_install = cost_install * 0.2086 * 1/12 
	gen cost_var = cost_maint/12 + cost_ope/12 
	drop cost_maint cost_ope
	label var cost_install "Capital costs (Rs, monthly amortized)"
	label var cost_var "Operating and maintenance costs (Rs, monthly)"
	
	* create a max efficiency column
	gen eff = . 
	label var eff "Emission reduction (%)"
	replace eff = 80 if apcd=="cyclone"
	replace eff = 99 if apcd=="bagfilter"
	replace eff = 94 if apcd=="scrubber"
	replace eff = 99.7 if apcd=="esp"

	* label apcd column
	label var apcd "APCD"

	* create emissions abatement 
	gen emissions_abate_month = emissions_inlet_month * (eff/100)
	label var emissions_abate_month "Emission abatement (kg/month)"
	
	* create monthly costs of abatement
	gen cost_abate_avg = (cost_install + cost_var)/emissions_abate_month  
	gen cost_abate_var = cost_var/emissions_abate_month
	label var cost_abate_avg "Average cost (Rs/kg)"
	label var cost_abate_var "Variable cost (Rs/kg)"
	
	* order of table 
	sort plant_boi_cap heatoutput
	order heatoutput plant_boi_cap apcd cost_install cost_var eff emissions_inlet_month emissions_abate_month cost_abate_avg cost_abate_var
	format cost_install cost_var emissions_abate_month emissions_inlet_month cost_abate_avg cost_abate_var %9.2f

* Create output table
	
	* loop over each boiler size panel
	clear matrix
	foreach size in 3 6 8 15 {

		* save all values for each apcd and cost var into matrices 
		tempname mat_cyclone mat_bagfilter mat_scrubber mat_esp
		ds cost_install cost_var eff emissions_inlet_month emissions_abate_month cost_abate_avg cost_abate_var 
		foreach var of varlist `r(varlist)' {
			foreach apcd in bagfilter cyclone scrubber esp {
				quietly: summarize `var' if apcd=="`apcd'" & plant_boi_cap==`size'
				local est_`apcd' `r(mean)'
				mat mat_`apcd' = nullmat(mat_`apcd'), `est_`apcd''
			}
		}
		
		* assemble overall panel matrix 
		mat panel_`size' = [mat_cyclone', mat_bagfilter', mat_scrubber', mat_esp']
		mat colnames panel_`size' = "_" "_" "_" "_" // "Cyclone" "Bag Filter" "Scrubber" "ESP"
		mat rownames panel_`size' = ///
			"Capital costs (Rs/month, amort.)" ///
			"Variable costs (Rs/month)" ///
			"Emission reduction (\%)" ///
			"Assumed pollution (kg/month)" ///
			"Emission abatement (kg/month)" ///
			"Average abatement cost (Rs/kg)" ///
			"Variable abatement cost (Rs/kg)" 
		matrix drop mat_cyclone mat_bagfilter mat_scrubber mat_esp
	}

		* create tables 
		local titles "&Cyclone & Bag Filter & Scrubber & ESP \\"
		local numbers "& (1) & (2) & (3) & (4) \\"
		local file "$PHONE_TABS/Table_F1.tex"
		# delimit ;
		
		local table_options 
				"varwidth(32) nomtitles booktabs 
				mlabels(,none) collabels(,none)
				prefoot(\addlinespace) nonotes";
		
		esttab m(panel_3, fmt(%9.2f)) using "`file'", replace
			`table_options'
			prehead("{" "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" "\begin{tabular}{l*{5}{c}}" "\toprule")
			posthead("`titles'" "`numbers'" "\midrule \addlinespace" "&\multicolumn{4}{c}{\textit{Total Boiler Capacity = 3 TPH}}\\ \addlinespace") 
			postfoot("") ;
			
		esttab m(panel_6, fmt(%9.2f)) using "`file'", append
			`table_options'
			prehead("&\multicolumn{4}{c}{\textit{Total Boiler Capacity = 6 TPH}}\\ \addlinespace") 
			posthead("")
			postfoot("") ;
			
		esttab m(panel_8, fmt(%9.2f)) using "`file'", append
			`table_options'
			prehead("&\multicolumn{4}{c}{\textit{Total Boiler Capacity = 8 TPH}}\\ \addlinespace") 
			posthead("") postfoot("") ;
			
		esttab m(panel_15, fmt(%9.2f)) using "`file'", append ///
			`table_options'
			prehead("&\multicolumn{4}{c}{\textit{Total Boiler Capacity = 15 TPH}}\\ \addlinespace")
			posthead("") postfoot("\bottomrule" "\end{tabular}""}")	;
			
		# delimit cr

restore 
